package com.kfm.wiki.interceptor;

import com.kfm.wiki.ex.BussinessException;
import com.kfm.wiki.util.Contains;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();

        // 跨域的预检查请求
        if (method.equalsIgnoreCase("OPTIONS")){
            return true;
        }
        // 登录后请求头中应包含 token 字段
        String token = request.getHeader("token");
        if (StringUtils.hasLength(token)){
            // 从 redis 中取 用户信息
            Object o = redisTemplate.opsForValue().get(Contains.REDIS_LOGIN_KEY_PRE + token);
            if (o != null){
                // 登录
                return true;
            }
        }

        throw new BussinessException("未登录 或 token 无效");
    }
}
